package com.jd.cms.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jd.cms.mapper.ContentMapper;
import com.jd.cms.mapper.ContentWrapper;
import com.jd.cms.pojo.Content;
import com.jd.cms.service.ContentService;
import com.jd.common.util.MysqlPageUtils;

@Service("contentService")
public class ContentServiceImpl implements ContentService {
	@Autowired
	private ContentMapper contentMapper;
	@Value("${REST_SERVER_URL}")
	private String REST_SERVER_URL;
	@Value("${SYNC_CACHE_CONTENT_URL}")
	private String SYNC_CACHE_CONTENT_URL;
	/*@Autowired
	private JedisApi jedisApi;*/
	@Value("${CONTENTS_HASH}")
	private String CONTENTS_HASH;
	@Value("${CONTENT_KEY}")
	private String CONTENT_KEY;

	@Override
	public List<Content> getContentsByCid(Content content, int page, int rows)
			throws Exception {
		ContentWrapper wrapper = new ContentWrapper();
		wrapper.setContent(content);
		wrapper.setMpu(new MysqlPageUtils(page, rows));
		return contentMapper.getContentsByCid(wrapper);
	}

	@Override
	public Long getCount(Content content) throws Exception {
		ContentWrapper contentWrapper = new ContentWrapper();
		contentWrapper.setContent(content);
		return contentMapper.getCount(contentWrapper);
	}

	// 添加内容
	@Override
	public int addContent(Content content) throws Exception {
		content.setCreated(new Date());
		content.setUpdated(new Date());
		int result = contentMapper.addContent(content);

		// 同步缓存
		/*
		 * try { String json =
		 * HttpClientUtil.doGet(REST_SERVER_URL+SYNC_CACHE_CONTENT_URL
		 * +"/"+content.getCategoryId()); } catch (Exception e) {
		 * e.printStackTrace(); }
		 */

		return result;
	}

	@Override
	public List<Content> getContentsByCid(long cid) throws Exception {
		// 先要判断缓存中是否有内容信息，如果有就获取直接返回，如果没有再查询数据库，并添加
		// 至缓存中. 请注意缓存代码不要影响正常代码的执行！！
		/*try {
			String json = jedisApi.hget(CONTENTS_HASH, CONTENT_KEY + cid);
			if (!StringUtils.isEmpty(json)) {
				List<Content> list = JsonUtils.jsonToList(json, Content.class);
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/

		// 查询数据库
		ContentWrapper contentWrapper = new ContentWrapper();
		Content content = new Content();
		content.setCategoryId(cid);
		contentWrapper.setContent(content);
		List<Content> contents = contentMapper.getContentsByCid(contentWrapper);

		/*// 添加缓存
		try {
			String json2 = JsonUtils.objectToJson(contents);
			jedisApi.hset(CONTENTS_HASH, CONTENT_KEY + cid, json2);
		} catch (Exception e) {
			e.printStackTrace();
		}*/

		return contents;
	}

}
